<template>
  <div class="refund-management">
    <div class="page-header">
      <div class="header-left">
        <h1>退款管理</h1>
        <p>管理众筹项目的退款申请</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-row :gutter="16">
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索项目名称、申请人..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-select v-model="statusFilter" placeholder="退款状态" clearable @change="handleFilter">
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateFilter"
          />
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-button @click="resetFilters">重置筛选</el-button>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 统计卡片 -->
    <el-row :gutter="24" class="stats-grid">
      <el-col :xs="24" :sm="12" :md="6" v-for="stat in statsData" :key="stat.key">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :class="stat.iconClass">
              <el-icon :size="24">
                <component :is="stat.icon" />
              </el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stat.value }}</h3>
              <p>{{ stat.label }}</p>
              <span class="stat-change" :class="stat.trend">
                {{ stat.change }}
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 退款申请表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table
        :data="paginatedRefunds"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="项目信息" min-width="250">
          <template #default="{ row }">
            <div class="project-info">
              <el-avatar :size="50" :src="row.projectImage" />
              <div class="project-details">
                <h4>{{ row.projectName }}</h4>
                <p>{{ row.projectCategory }}</p>
                <el-tag size="small" :type="getProjectStatusType(row.projectStatus)">
                  {{ getProjectStatusText(row.projectStatus) }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="申请人" width="150">
          <template #default="{ row }">
            <div class="applicant-info">
              <div class="applicant-name">{{ row.applicantName }}</div>
              <div class="applicant-phone">{{ row.applicantPhone }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="退款金额" width="120" align="center">
          <template #default="{ row }">
            <span class="amount">¥{{ formatNumber(row.refundAmount) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="申请时间" width="150" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.applyTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="退款状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getRefundStatusType(row.refundStatus)" size="small">
              {{ getRefundStatusText(row.refundStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="退款原因" width="200">
          <template #default="{ row }">
            <el-tooltip :content="row.refundReason" placement="top">
              <span class="reason-text">{{ row.refundReason }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="viewRefund(row)">
              查看
            </el-button>
            <el-button 
              v-if="row.refundStatus === 'pending'" 
              type="success" 
              size="small" 
              link 
              @click="approveRefund(row)"
            >
              通过
            </el-button>
            <el-button 
              v-if="row.refundStatus === 'pending'" 
              type="danger" 
              size="small" 
              link 
              @click="rejectRefund(row)"
            >
              拒绝
            </el-button>
            <el-button 
              v-if="row.refundStatus === 'approved'" 
              type="warning" 
              size="small" 
              link 
              @click="processRefund(row)"
            >
              处理退款
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredRefunds.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 批量操作 -->
    <div v-if="selectedRefunds.length > 0" class="batch-actions">
      <el-alert
        :title="`已选择 ${selectedRefunds.length} 条退款申请`"
        type="info"
        show-icon
        closable
      >
        <template #default>
          <el-button type="success" size="small" @click="batchApprove">批量通过</el-button>
          <el-button type="danger" size="small" @click="batchReject">批量拒绝</el-button>
          <el-button type="warning" size="small" @click="batchExport">批量导出</el-button>
        </template>
      </el-alert>
    </div>
    
    <!-- 查看退款详情对话框 -->
    <el-dialog
      v-model="showRefundDetail"
      title="退款详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="selectedRefund" class="refund-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称">{{ selectedRefund.projectName }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ selectedRefund.applicantName }}</el-descriptions-item>
          <el-descriptions-item label="退款金额">¥{{ formatNumber(selectedRefund.refundAmount) }}</el-descriptions-item>
          <el-descriptions-item label="退款状态">
            <el-tag :type="getRefundStatusType(selectedRefund.refundStatus)">
              {{ getRefundStatusText(selectedRefund.refundStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDateTime(selectedRefund.applyTime) }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedRefund.applicantPhone }}</el-descriptions-item>
          <el-descriptions-item label="退款原因" :span="2">{{ selectedRefund.refundReason }}</el-descriptions-item>
          <el-descriptions-item v-if="selectedRefund.adminRemark" label="管理员备注" :span="2">{{ selectedRefund.adminRemark }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRefundDetail = false">关闭</el-button>
          <el-button 
            v-if="selectedRefund && selectedRefund.refundStatus === 'pending'"
            type="success" 
            @click="approveRefund(selectedRefund)"
          >
            通过申请
          </el-button>
          <el-button 
            v-if="selectedRefund && selectedRefund.refundStatus === 'pending'"
            type="danger" 
            @click="rejectRefund(selectedRefund)"
          >
            拒绝申请
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 拒绝退款对话框 -->
    <el-dialog
      v-model="showRejectDialog"
      title="拒绝退款申请"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="拒绝原因" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRejectDialog = false">取消</el-button>
          <el-button type="danger" @click="confirmReject">确认拒绝</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Download, 
  Search, 
  Money, 
  User, 
  TrendCharts,
  WarningFilled
} from '@element-plus/icons-vue'

const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const selectedRefunds = ref([])
const showRefundDetail = ref(false)
const selectedRefund = ref(null)
const showRejectDialog = ref(false)
const rejectForm = reactive({
  reason: '',
  refundId: null
})

// 统计数据
const statsData = reactive([
  {
    key: 'total',
    label: '总退款申请',
    value: 156,
    change: '+8% 本月',
    trend: 'positive',
    icon: WarningFilled,
    iconClass: 'total-icon'
  },
  {
    key: 'amount',
    label: '总退款金额',
    value: '¥89,500',
    change: '+12% 本月',
    trend: 'positive',
    icon: Money,
    iconClass: 'amount-icon'
  },
  {
    key: 'pending',
    label: '待处理申请',
    value: 23,
    change: '-5% 本月',
    trend: 'negative',
    icon: User,
    iconClass: 'pending-icon'
  },
  {
    key: 'rate',
    label: '退款率',
    value: '5.2%',
    change: '+0.3% 本月',
    trend: 'positive',
    icon: TrendCharts,
    iconClass: 'rate-icon'
  }
])

// 模拟退款数据
const refunds = ref([
  {
    id: 1,
    projectName: '智能手表众筹',
    projectCategory: '科技',
    projectStatus: 'active',
    projectImage: 'https://via.placeholder.com/50x50/667eea/ffffff?text=⌚',
    applicantName: '张三',
    applicantPhone: '138****0001',
    refundAmount: 299,
    applyTime: '2024-01-25 14:30:00',
    refundStatus: 'pending',
    refundReason: '产品功能与宣传不符，希望退款',
    adminRemark: ''
  },
  {
    id: 2,
    projectName: '环保水杯设计',
    projectCategory: '设计',
    projectStatus: 'success',
    projectImage: 'https://via.placeholder.com/50x50/43e97b/ffffff?text=🥤',
    applicantName: '李四',
    applicantPhone: '138****0002',
    refundAmount: 199,
    applyTime: '2024-01-24 09:15:00',
    refundStatus: 'approved',
    refundReason: '个人原因，无法继续支持项目',
    adminRemark: '用户主动申请，已通过'
  },
  {
    id: 3,
    projectName: '手工巧克力制作',
    projectCategory: '美食',
    projectStatus: 'active',
    projectImage: 'https://via.placeholder.com/50x50/f093fb/ffffff?text=🍫',
    applicantName: '王五',
    applicantPhone: '138****0003',
    refundAmount: 99,
    applyTime: '2024-01-25 16:45:00',
    refundStatus: 'rejected',
    refundReason: '产品质量问题',
    adminRemark: '产品已发货，质量问题需提供证据'
  },
  {
    id: 4,
    projectName: '数字艺术画作',
    projectCategory: '艺术',
    projectStatus: 'pending',
    projectImage: 'https://via.placeholder.com/50x50/4facfe/ffffff?text=🎨',
    applicantName: '赵六',
    applicantPhone: '138****0004',
    refundAmount: 599,
    applyTime: '2024-01-20 11:20:00',
    refundStatus: 'refunded',
    refundReason: '项目延期，不想继续等待',
    adminRemark: '已退款到原支付账户'
  },
  {
    id: 5,
    projectName: '创意台灯设计',
    projectCategory: '设计',
    projectStatus: 'failed',
    projectImage: 'https://via.placeholder.com/50x50/ff9a9e/ffffff?text=💡',
    applicantName: '钱七',
    applicantPhone: '138****0005',
    refundAmount: 399,
    applyTime: '2024-01-23 13:10:00',
    refundStatus: 'pending',
    refundReason: '项目失败，要求退款',
    adminRemark: ''
  }
])

// 计算属性
const filteredRefunds = computed(() => {
  let filtered = refunds.value
  
  if (searchQuery.value) {
    filtered = filtered.filter(refund => 
      refund.projectName.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      refund.applicantName.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }
  
  if (statusFilter.value) {
    filtered = filtered.filter(refund => refund.refundStatus === statusFilter.value)
  }
  
  if (dateRange.value && dateRange.value.length === 2) {
    filtered = filtered.filter(refund => {
      const applyDate = refund.applyTime.split(' ')[0]
      return applyDate >= dateRange.value[0] && applyDate <= dateRange.value[1]
    })
  }
  
  return filtered
})

const paginatedRefunds = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredRefunds.value.slice(start, end)
})

// 方法
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

const formatDateTime = (dateTimeStr) => {
  return new Date(dateTimeStr).toLocaleString('zh-CN')
}

const getProjectStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    active: 'success',
    success: 'primary',
    failed: 'danger'
  }
  return typeMap[status] || 'info'
}

const getProjectStatusText = (status) => {
  const textMap = {
    pending: '待审核',
    active: '众筹中',
    success: '成功',
    failed: '失败'
  }
  return textMap[status] || status
}

const getRefundStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    refunded: 'info'
  }
  return typeMap[status] || 'info'
}

const getRefundStatusText = (status) => {
  const textMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝',
    refunded: '已退款'
  }
  return textMap[status] || status
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleDateFilter = () => {
  currentPage.value = 1
}

const resetFilters = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  dateRange.value = []
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const handleSelectionChange = (selection) => {
  selectedRefunds.value = selection
}

const viewRefund = (refund) => {
  selectedRefund.value = refund
  showRefundDetail.value = true
}

const approveRefund = async (refund) => {
  try {
    await ElMessageBox.confirm(
      `确定要通过 ${refund.applicantName} 对项目"${refund.projectName}"的退款申请吗？`,
      '确认通过',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    refund.refundStatus = 'approved'
    refund.adminRemark = '管理员已通过退款申请'
    ElMessage.success('退款申请已通过')
  } catch {
    // 用户取消操作
  }
}

const rejectRefund = (refund) => {
  rejectForm.refundId = refund.id
  rejectForm.reason = ''
  showRejectDialog.value = true
}

const confirmReject = async () => {
  if (!rejectForm.reason.trim()) {
    ElMessage.warning('请输入拒绝原因')
    return
  }
  
  const refund = refunds.value.find(r => r.id === rejectForm.refundId)
  if (refund) {
    refund.refundStatus = 'rejected'
    refund.adminRemark = rejectForm.reason
    ElMessage.success('退款申请已拒绝')
    showRejectDialog.value = false
  }
}

const processRefund = async (refund) => {
  try {
    await ElMessageBox.confirm(
      `确定要处理 ${refund.applicantName} 的退款吗？金额：¥${formatNumber(refund.refundAmount)}`,
      '确认退款',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    refund.refundStatus = 'refunded'
    refund.adminRemark = '已退款到原支付账户'
    ElMessage.success('退款处理成功')
  } catch {
    // 用户取消操作
  }
}

const exportData = () => {
  ElMessage.success('数据导出功能开发中...')
}

const batchApprove = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量通过选中的 ${selectedRefunds.value.length} 条退款申请吗？`,
      '确认批量通过',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    selectedRefunds.value.forEach(refund => {
      if (refund.refundStatus === 'pending') {
        refund.refundStatus = 'approved'
        refund.adminRemark = '批量通过'
      }
    })
    ElMessage.success('批量通过成功')
  } catch {
    // 用户取消操作
  }
}

const batchReject = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量拒绝选中的 ${selectedRefunds.value.length} 条退款申请吗？`,
      '确认批量拒绝',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    selectedRefunds.value.forEach(refund => {
      if (refund.refundStatus === 'pending') {
        refund.refundStatus = 'rejected'
        refund.adminRemark = '批量拒绝'
      }
    })
    ElMessage.success('批量拒绝成功')
  } catch {
    // 用户取消操作
  }
}

const batchExport = () => {
  ElMessage.success(`批量导出 ${selectedRefunds.value.length} 条记录`)
}

onMounted(() => {
  console.log('退款管理页面已加载')
})
</script>

<style scoped>
.refund-management {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-left h1 {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin-bottom: 4px;
}

.header-left p {
  color: #666;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 12px;
}

.stats-grid {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 16px;
  border: 1px solid rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.total-icon {
  background: linear-gradient(135deg, #ff9a9e, #fecfef);
}

.amount-icon {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.pending-icon {
  background: linear-gradient(135deg, #fa709a, #fee140);
}

.rate-icon {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.stat-info h3 {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  margin: 0 0 4px 0;
}

.stat-info p {
  color: #666;
  font-size: 14px;
  margin: 0 0 8px 0;
}

.stat-change {
  font-size: 12px;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 6px;
}

.stat-change.positive {
  background: rgba(76, 175, 80, 0.1);
  color: #4caf50;
}

.stat-change.negative {
  background: rgba(244, 67, 54, 0.1);
  color: #f44336;
}

.table-card {
  border-radius: 12px;
  margin-bottom: 24px;
}

.project-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.project-details h4 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
}

.project-details p {
  color: #666;
  font-size: 14px;
  margin: 0 0 8px 0;
}

.applicant-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.applicant-name {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.applicant-phone {
  color: #666;
  font-size: 12px;
}

.amount {
  font-weight: 600;
  color: #333;
}

.reason-text {
  color: #666;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 180px;
  display: inline-block;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.batch-actions {
  margin-top: 16px;
}

.refund-detail {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #f8f9fa;
}

:deep(.el-card__body) {
  padding: 20px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .project-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .project-details p {
    max-width: none;
  }
}
</style> 